import sys
from pathlib import Path

import vlc
from PyQt5.QtWidgets import QWidget, QApplication


class VideoWidget(QWidget):

    def __init__(self, instance=vlc.Instance()):
        super().__init__()
        self.setGeometry(0, 0, 1200, 800)

        self.hardwareDecode = True  # 硬解
        self.media = None  # 媒体
        self.audioChannel = 0  # 0 原始音效  5 杜比音效
        self.hiding = False  # 隐藏
        self.progress = 0  # 视频进度
        self.pause = True  # 是否暂停
        self.volume = 100
        self.video = ""
        self.video_list = []

        self.instance = instance
        self.player = None

        self.initVlc()

    def initVlc(self):
        """初始化Vlc"""
        self.player = self.instance.media_player_new()
        self.player.video_set_mouse_input(False)
        self.player.video_set_key_input(False)
        self.player.event_manager().event_attach(vlc.EventType(256), self.mediaPlayerEndReached)
        self.player.set_hwnd(self.winId())

    def mediaPlayerEndReached(self, event):
        """视频播放完"""
        pass

    def autoWindowSize(self, video_path):
        """窗口大小自适应"""
        pass

    def setMedia(self, video_path: Path):
        """设置视频"""
        if self.hardwareDecode:
            self.media = self.instance.media_new(video_path, 'avcodec-hw=any')  # 设置vlc并硬解播放
        else:
            self.media = self.instance.media_new(video_path, 'avcodec-hw=none')  # 软解  vlc3.0似乎不起作用?
        self.player.set_media(self.media)  # 设置视频
        self.player.audio_set_channel(self.audioChannel)
        self.player.play()
        self.autoWindowSize(video_path)
        self.video = video_path.__str__()
        self.pause = False

    def setAudio(self, volume: int):
        """设置音量"""
        self.volume = volume
        self.player.audio_set_volume(volume)

    def pauseVideo(self):
        """暂停视频"""
        if self.pause:
            return
        self.progress = self.player.get_time()
        self.pause = True
        self.player.pause()

    def startVideo(self):
        """播放视频"""
        if not self.pause:
            return
        self.pause = False
        self.player.set_pause(0)

    def setTime(self, progress):
        self.player.set_time(progress)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = VideoWidget()
    window.setMedia(Path("cache/BV1kJ4m1e7zD.mp4"))
    window.show()
    app.exec_()

